import React from 'react';
import styles from './upload.scss';
import {request} from 'utils/request';
import {Button, Progress, message} from 'antd';
import actions from 'store/actions/img-repo';
import {getGlobalEvent} from 'utils/eventEmitter';
const eventBus = getGlobalEvent();

class Upload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      percent: 0,
      showProgress: false
    };
  }

  async getSignature() {
    const res = await request({
      url: '/api/common/ossSignature',
      method: 'get'
    });
    return res;
  }

  render() {
    const btnId = this.props.btnId || 'browse';
    return (
      <div className={styles.handlers}>
        <Button type="primary" id={btnId}>
          上传图片
        </Button>
        {this.state.showProgress && (
          <div className={styles.progressWrap}>
            <Progress percent={this.state.percent} />
          </div>
        )}
      </div>
    );
  }

  async componentDidMount() {
    const that = this;
    const {dispatch, currTag} = this.props;
    const btnId = this.props.btnId || 'browse';
    this.uploader = new plupload.Uploader({
      runtimes: 'html5',
      browse_button: btnId,
      url: 'http://oss.aliyuncs.com',
      filters: {
        mime_types: [{title: 'Image files', extensions: 'jpg,gif,png,bmp,jpeg'}],
        max_file_size: '10mb', //最大只能上传10mb的文件
        prevent_duplicates: true //不允许选取重复文件
      },
      init: {
        FilesAdded: async function(up, files) {
          const arr = files[0].name.split('.');
          const suffix = arr[arr.length - 1];
          that.setState({
            showProgress: true
          });
          const res = await that.getSignature();
          that.fileName = new Date().getTime();
          that.imgUrl = res.data.startsWith + that.fileName + '.' + suffix;
          up.setOption({
            url: res.data.host,
            multipart_params: {
              OSSAccessKeyId: res.data.accessKeyId,
              policy: res.data.policy,
              key: that.imgUrl,
              success_action_status: '200',
              signature: res.data.signature
            }
          });
          up.start();
        },
        UploadProgress: function(up, file) {
          that.setState({
            percent: file.percent
          });
        },
        FileUploaded: async function(up, file, info) {
          that.setState({
            showProgress: false
          });
          if (info.status === 200) {
            message.success('上传成功');
            const res = await dispatch(
              actions.addImgs({
                tagId: that.props.currTag,
                url: that.imgUrl
              })
            );
            if (res.code === '0') {
              eventBus.emit('onImgUploaded', {
                id: res.data.id,
                url: that.imgUrl
              });
            }
          } else {
            message.error(`上传失败：${info.response}`);
          }
        }
      }
    });
    this.uploader.init();
  }
}

export default Upload;
